package leetcode.day_2020_11_30_12_6;

import leetcode.Head;
import leetcode.ListNode;

/**
 * 24. 两两交换链表中的节点
 */
public class L_24 {
    public static void main(String[] args) {
        System.out.println(swapPairs(Head.genList()).val);
    }

    public static ListNode swapPairs(ListNode head) {
        // 空链表或者一个元素
        if(head == null || head.next == null) {
            return head;
        }
        ListNode root = new ListNode(-1);
        root.next = head;
        ListNode curr = root;
        ListNode quick = head.next;
        ListNode slow = head;
        while (quick!= null) {
            // 进行翻转
            slow.next = quick.next;
            quick.next = slow;
            // 翻转后进行复位
            ListNode demo = slow;
            slow = quick;
            quick = demo;
            // 进行链表的连接
            curr.next = slow;
            // 向后移动指针
            if(quick.next!=null){
                quick = quick.next.next;
                slow = slow.next.next;
                curr = curr.next.next;
            }else{
                break;
            }
        }
        return root.next;
    }
}
